package ${packageName};

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import com.querydsl.core.BooleanBuilder;
import com.maxtropy.iacp.utils.PageUtils;
import com.maxtropy.iacp.controller.base.BaseController;
import org.springframework.data.domain.Pageable;
import ${entity.packageName}.${entity.className};
import ${lastRenderResponse.form.packageName}.${lastRenderResponse.form.className};
import ${lastRenderResponse.service.packageName}.${lastRenderResponse.service.className};
<#list imports as import>
import ${import};
</#list>

import java.security.Principal;

/**
 * controller for ${entity.className} generated by jpa-codegen
 * ${comments}
 *
 * @author ${author}
 * Created On ${date}.
 */
@RestController
@RequestMapping("/${entity.className?uncap_first}")
public class ${className} extends BaseController {

    @Autowired
    private ${lastRenderResponse.service.className} ${lastRenderResponse.service.className?uncap_first};

    @PostMapping
    public ResponseEntity<?> create(@RequestBody @Validated ${lastRenderResponse.form.className} form) {
        ${entity.className} ${entity.className?uncap_first} = ${lastRenderResponse.service.className?uncap_first}.create(form);
        return created(${entity.className?uncap_first});
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(${entity.id.className} id) {
        ${lastRenderResponse.service.className?uncap_first}.delete(id);
        return deleted();
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> update(@RequestBody @Validated ${lastRenderResponse.form.className} form,
                                    @PathVariable("id") ${entity.id.className} id) {
        ${entity.className} ${entity.className?uncap_first} = ${lastRenderResponse.service.className?uncap_first}.update(form, id);
        return created(${entity.className?uncap_first});
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> get(@PathVariable("id") ${entity.id.className} id) {
        ${entity.className} ${entity.className?uncap_first} = ${lastRenderResponse.service.className?uncap_first}.get(id);
        return ok(${entity.className?uncap_first});
    }

    @GetMapping
    public ResponseEntity<?> page(@RequestParam(value = "page", required = false) Integer page,
                                  @RequestParam(value = "per_page", required = false) Integer perPage,
                                  @RequestParam(value = "fields", required = false) String fields,
                                  Principal principal) {
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        Pageable pageable = PageUtils.page(page, perPage, false, "updateTime");
        // TODO
        return ok(${lastRenderResponse.service.className?uncap_first}.page(booleanBuilder, pageable), fields);
    }

}